package vashion.azeroth.core.manager.item;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;

import vashion.azeroth.common.http.HttpContentGetter;
import vashion.azeroth.common.math.BigDecimalUtil;
import vashion.azeroth.contant.AzerothConstants;
import vashion.azeroth.contant.ExchangeRateConstants;
import vashion.azeroth.contant.GenericErrorEnum;
import vashion.azeroth.contant.MemberErrorEnum;
import vashion.azeroth.contant.item.ItemStatusEnum;
import vashion.azeroth.core.item.pojo.ForestPropertyValueDO;
import vashion.azeroth.core.item.pojo.ItemDO;
import vashion.azeroth.core.item.pojo.ItemLenuxBrandDO;
import vashion.azeroth.core.item.pojo.ItemLenuxForestDO;
import vashion.azeroth.core.item.pojo.ItemSkuDO;
import vashion.azeroth.core.item.pojo.PropertyValueDO;
import vashion.azeroth.core.item.query.ItemQueryDO;
import vashion.azeroth.core.lenux.pojo.LenuxApiResult;
import vashion.azeroth.core.lenux.pojo.LenuxItem;
import vashion.azeroth.core.lenux.pojo.LenuxProduct;
import vashion.azeroth.core.manager.forest.BaseForestPropertyManager;
import vashion.azeroth.core.manager.personal.PersonalMemberManager;
import vashion.azeroth.core.personal.pojo.PersonalMember;
import vashion.azeroth.core.result.ApiResult;

@Service
public class LenuxItemWriteManager {

	private static final String ITALIAN_MALE = "Uomo";
	private static final String ITALIAN_FEMALE = "Donna";

	private static final String AUTUNNO_INVERNO_17 = "Autunno/Inverno17";

	private static final String PRIMAVERA_ESTATE_17 = "Primavera/Estate17";

	private static final String AUTUNNO_INVERNO_16 = "Autunno/Inverno2016";

	private static final String PRIMAVERA_ESTATE_16 = "Primavera/Estate2016";

	private static final Double AUTUNNO_INVERNO_17_DISCOUNT = 0.77;

	private static final Double PRIMAVERA_ESTATE_17_DISCOUNT = 0.54;

	private static final Double AUTUNNO_INVERNO_16_DISCOUNT = 0.40;

	private static final Double PRIMAVERA_ESTATE_16_DISCOUNT = AUTUNNO_INVERNO_16_DISCOUNT;

	private final static Logger log = LoggerFactory.getLogger(LenuxItemWriteManager.class);

	@Autowired
	private BaseItemManager baseItemManager;

	@Autowired
	private BaseItemSkuManager baseItemSkuManager;

	@Autowired
	private ItemWriteManager itemWriteManager;

	@Autowired
	private ItemLenuxBrandManager itemLenuxBrandManager;

	@Autowired
	private ItemLenuxForestManager itemLenuxForestManager;

	@Autowired
	private PersonalMemberManager personalMemberManager;

	@Autowired
	private BaseForestPropertyManager baseForestPropertyManager;

	@Autowired
	private BaseItemForestBrandManager baseItemForestBrandManager;

	/**
	 * @param lenuxProduct
	 * @param memberName
	 * @return 保存结果
	 */
	public ApiResult<Boolean> publishItem(LenuxProduct lenuxProduct, String memberName) {
		if (null == lenuxProduct || null == memberName) {
			return ApiResult.newSuccessResult(false);
		}
		// 查找用户
		PersonalMember member = personalMemberManager.getMemberByName(memberName);
		if (null == member) {
			return ApiResult.newErrorResult(MemberErrorEnum.NOT_EXISTID.getErrorCode(),
					MemberErrorEnum.NOT_EXISTID.getErrorMessage());
		}
		// 转换商品
		ItemDO item = this.lenuxProduct2ItemDO(lenuxProduct, member);
		// 如果商品转换不成功，不保存
		if (null == item) {
			return ApiResult.newSuccessResult(false);
		}
		// 查询商品是否存在
		ItemQueryDO itemDoByItemCode = new ItemQueryDO();
		itemDoByItemCode.setItemCode(item.getItemCode());
		itemDoByItemCode.setUserId(member.getMemberId());
		List<ItemDO> itemList = baseItemManager.querySameCodeItem(itemDoByItemCode);
		int totalStock = 0;
		boolean result = false;
		// 如果存在，update商品
		if (null != itemList && itemList.size() == 1) {
			ItemDO itemOrigin = itemList.get(0);
			totalStock = itemOrigin.getStock();
			// 查询商品的property value
			ApiResult<ForestPropertyValueDO> ForestPropertyResult = baseForestPropertyManager
					.getForestPropertyValues(item.getCategoryId(), AzerothConstants.ItemForestProperty.NORMAL);
			if (null != ForestPropertyResult && ForestPropertyResult.isSuccess()
					&& null != ForestPropertyResult.getData()) {
				ForestPropertyValueDO forestPropertyValueDO = ForestPropertyResult.getData();
				List<PropertyValueDO> propertyValueDOListOrigial = forestPropertyValueDO.getPropertyValueDOList();

				for (PropertyValueDO propertyValueDOTemp : item.getFeatureValueDOList()) {
					// 查询商品的property value
					PropertyValueDO propertyValueDO = findSystemPropertyValue(propertyValueDOListOrigial,
							propertyValueDOTemp);
					// 如果数据库中没有对应的尺寸，不保存
					if (null == propertyValueDO)
						continue;
					// 查询出对应的SKU
					ItemSkuDO itemSkuDO = new ItemSkuDO();
					itemSkuDO.setItemId(itemOrigin.getId());
					itemSkuDO.setPropertyValueIdArr(String.valueOf(propertyValueDO.getId()));
					List<ItemSkuDO> itemSkuList = baseItemSkuManager.find(itemSkuDO);
					long originalSkuStock = 0;
					if (null != itemSkuList && itemSkuList.size() == 1) {
						// 有对应的sku，更新sku
						itemSkuDO = itemSkuList.get(0);
						// 更新sku的库存
						originalSkuStock = itemSkuDO.getStock();
						itemSkuDO.setStock(propertyValueDOTemp.getStock());
						// itemSkuDO.setColor(propertyValueDOTemp.getColor());
						result = baseItemSkuManager.update(itemSkuDO) > 0;
					} else if (null == itemSkuList || itemSkuList.size() == 0) {
						// 无对应的sku，新保存sku
						itemSkuDO.setStock(propertyValueDOTemp.getStock());
						itemSkuDO.setUserId(itemOrigin.getUserId());
						itemSkuDO.setColor(propertyValueDOTemp.getColor());
						itemSkuDO.setStatus(AzerothConstants.Item.NORMAL);
						result = (null != baseItemSkuManager.save(itemSkuDO));
						originalSkuStock = 0;
					} else {
						continue;
					}
					if (result) {
						totalStock = (int) (itemOrigin.getStock() - originalSkuStock + propertyValueDOTemp.getStock());
					}
				}
				// 更新商品的总库存
				ItemDO itemUpdate = new ItemDO();
				itemUpdate.setId(itemOrigin.getId());
				itemUpdate.setStock(totalStock);
				if (totalStock <= 0) {
					itemUpdate.setStatus(ItemStatusEnum.SYSTEM_DELETE.getStatus());
				}
				// itemUpdate.setPriceDisplay(item.getPriceDisplay());
				// itemUpdate.setMaterial(lenuxProduct.getMaterial());
				// itemUpdate.setSeason(lenuxProduct.getSeason());
				// itemUpdate.setSpu(lenuxProduct.getSpu());
				//itemUpdate.setCategoryId(item.getCategoryId());
				//itemUpdate.setCategoryFullTitle(item.getCategoryFullTitle());
				result = itemWriteManager.updateItem(itemUpdate, null, itemOrigin.getUserId()).isSuccess();
			}
		}
		// 如果不存在，save商品
		else if (null == itemList || itemList.size() == 0) {
			List<ItemSkuDO> skuDOList = Lists.<ItemSkuDO>newArrayList();
			// 查询商品的property value
			ApiResult<ForestPropertyValueDO> ForestPropertyResult = baseForestPropertyManager
					.getForestPropertyValues(item.getCategoryId(), AzerothConstants.ItemForestProperty.NORMAL);
			if (null != ForestPropertyResult && ForestPropertyResult.isSuccess()
					&& null != ForestPropertyResult.getData()) {
				ForestPropertyValueDO forestPropertyValueDO = ForestPropertyResult.getData();
				List<PropertyValueDO> propertyValueDOListOrigial = forestPropertyValueDO.getPropertyValueDOList();

				for (PropertyValueDO propertyValueDOTemp : item.getFeatureValueDOList()) {
					// 查询商品的property value
					PropertyValueDO propertyValueDO = findSystemPropertyValue(propertyValueDOListOrigial,
							propertyValueDOTemp);
					// 如果数据库中没有对应的尺寸，不保存
					if (null == propertyValueDO)
						continue;
					// 新建sku
					ItemSkuDO itemSkuDO = new ItemSkuDO();
					itemSkuDO.setStock(propertyValueDOTemp.getStock());
					itemSkuDO.setUserId(member.getMemberId());
					itemSkuDO.setPropertyValueIdArr(String.valueOf(propertyValueDO.getId()));
					itemSkuDO.setColor(propertyValueDOTemp.getColor());
					itemSkuDO.setStatus(AzerothConstants.Item.NORMAL);
					skuDOList.add(itemSkuDO);
					totalStock = (int) (totalStock + propertyValueDOTemp.getStock());

				}
				// 设置商品的总库存，发布新商品
				item.setStock(totalStock);
				if (totalStock <= 0) {
					item.setStatus(ItemStatusEnum.SYSTEM_DELETE.getStatus());
				}
				result = itemWriteManager.publishItem(item, skuDOList, null, member.getMemberId()).isSuccess();
			}
		} else {
			return ApiResult.newErrorResult(GenericErrorEnum.SYSTEM_ERROR.getErrorCode(),
					GenericErrorEnum.SYSTEM_ERROR.getErrorMessage());
		}
		return ApiResult.newSuccessResult(result);
	}

	/**
	 * @param propertyValueDOListOrigial
	 * @param propertyValueDOTemp
	 * @return
	 */
	private PropertyValueDO findSystemPropertyValue(List<PropertyValueDO> propertyValueDOListOrigial,
			PropertyValueDO propertyValueDOTemp) {
		PropertyValueDO propertyValueDO = null;
		// 只有一个默认尺寸
		if (StringUtils.isBlank(propertyValueDOTemp.getValue()) || 1 == propertyValueDOListOrigial.size()) {
			propertyValueDO = propertyValueDOListOrigial.get(0);
		} else {
			// 有多个尺寸
			for (PropertyValueDO propertyValueDOOrigialTemp : propertyValueDOListOrigial) {
				if (propertyValueDOOrigialTemp.getValue().equalsIgnoreCase(propertyValueDOTemp.getValue())) {
					propertyValueDO = propertyValueDOOrigialTemp;
				}
			}
		}
		return propertyValueDO;
	}

	private ItemDO lenuxProduct2ItemDO(LenuxProduct lenuxProduct, PersonalMember member) {
		ItemDO itemDO = new ItemDO();
		itemDO.setUserId(member.getMemberId());
		itemDO.setMemberName(member.getMemberName());
		itemDO.setPriceCurno(ExchangeRateConstants.CurNos.EUR);
		itemDO.setStatus(ItemStatusEnum.SYSTEM_DELETE.getStatus());
		// 设置适用性别
		if (ITALIAN_FEMALE.equalsIgnoreCase(lenuxProduct.getGender())) {
			itemDO.setFeature(AzerothConstants.Item.FEMALE.toString());
		} else if (ITALIAN_MALE.equalsIgnoreCase(lenuxProduct.getGender())) {
			itemDO.setFeature(AzerothConstants.Item.MALE.toString());
		} else {
			itemDO.setFeature(AzerothConstants.Item.ALL.toString());
		}
		// 设置品牌
		ApiResult<ItemLenuxBrandDO> itemLenuxBrandDOResult = itemLenuxBrandManager
				.findByLenuxBrandTitle(lenuxProduct.getBrand());
		if (itemLenuxBrandDOResult.isSuccess() && null != itemLenuxBrandDOResult.getData()) {
			itemDO.setBrandId(itemLenuxBrandDOResult.getData().getBrandId());
			itemDO.setBrandTitle(itemLenuxBrandDOResult.getData().getBrandTitle());
		} else {
			return null;
		}

		// 设置类目
		ApiResult<List<ItemLenuxForestDO>> itemLenuxForestListResult = itemLenuxForestManager
				.findByLenuxCataTitle(lenuxProduct.getCats());
		ItemLenuxForestDO featureItemLenuxForest = null;
		ItemLenuxForestDO allFeatureItemLenuxForest = null;
		if (itemLenuxForestListResult.isSuccess() && null != itemLenuxForestListResult.getData()
				&& !itemLenuxForestListResult.getData().isEmpty()) {
			for (ItemLenuxForestDO itemLenuxForestDOTemp : itemLenuxForestListResult.getData()) {
				// 找出适用人群相同的类目
				if (itemLenuxForestDOTemp.getFeature().equals(itemDO.getFeature())) {
					featureItemLenuxForest = itemLenuxForestDOTemp;
				}
				if (itemLenuxForestDOTemp.getFeature().equals(AzerothConstants.Item.ALL.toString())) {
					allFeatureItemLenuxForest = itemLenuxForestDOTemp;
				}
			}
			// 如果没有相同适用人群的类目，则设置成通用类目
			if (null == featureItemLenuxForest) {
				featureItemLenuxForest = allFeatureItemLenuxForest;
			}
			if (null != featureItemLenuxForest) {
				itemDO.setCategoryId(featureItemLenuxForest.getForestId());
				itemDO.setCategoryFullTitle(featureItemLenuxForest.getForestTitle());
			}
		} else {
			return null;
		}

		// 设置品牌和类目的关联
		// if (itemLenuxBrandDOResult.isSuccess() && null !=
		// itemLenuxBrandDOResult.getData()
		// && itemLenuxForestDOResult.isSuccess() && null !=
		// itemLenuxForestDOResult.getData()) {
		// if (itemLenuxBrandDOResult.getData().getBrandId() != 70) {
		// ItemBrandDO brandDO = new ItemBrandDO();
		// brandDO.setId(itemLenuxBrandDOResult.getData().getBrandId());
		// brandDO.setTitle(itemLenuxBrandDOResult.getData().getBrandTitle());
		// brandDO.setStatus(AzerothConstants.ItemBrand.NORMAL);
		// ForestDO forestDO = new ForestDO();
		// forestDO.setId(itemLenuxForestDOResult.getData().getForestId());
		// forestDO.setTitle(itemLenuxForestDOResult.getData().getForestTitle());
		// forestDO.setStatus(AzerothConstants.ItemForest.NORMAL);
		// baseItemForestBrandManager.publishBrandForest(brandDO, forestDO,
		// member.getMemberId());
		// }
		// }

		// 设置图片
		String picString = lenuxProduct.getImgs();
		if (picString.indexOf(';') > 0) {
			itemDO.setPic(picString.substring(0, picString.indexOf(';')));
			itemDO.setDescPic(
					picString.substring(picString.indexOf(';') + 1).replaceAll(";", ",").replaceAll("\\s*", ""));
		} else {
			itemDO.setPic(picString);
		}

		itemDO.setItemCode(lenuxProduct.getOriCode());
		itemDO.setItemDesc(lenuxProduct.getTitle());
		// 设置材质、季节、spu
		itemDO.setMaterial(lenuxProduct.getMaterial());
		itemDO.setSeason(lenuxProduct.getSeason());
		itemDO.setSpu(lenuxProduct.getSpu());
		// 设置sku
		List<PropertyValueDO> propertyValueDOList = Lists.<PropertyValueDO>newArrayList();
		if (null != lenuxProduct.getItems()) {
			for (LenuxItem lenuxItemTemp : lenuxProduct.getItems()) {
				PropertyValueDO propertyValueDO = new PropertyValueDO();
				// 去除尺寸中多余的0
				String size = lenuxItemTemp.getSize();
				while (true) {
					if (null != size && size.startsWith("0")) {
						size = size.substring(1);
					} else {
						break;
					}
				}
				// 代替‘,’为‘.’
				size = size.replaceAll(",", ".");
				propertyValueDO.setValue(size);
				propertyValueDO.setStock(lenuxItemTemp.getNum());
				// 设置颜色
				propertyValueDO.setColor(lenuxItemTemp.getColor());
				propertyValueDOList.add(propertyValueDO);
				// 设置价格
				itemDO.setReferencePriceDisplay(lenuxItemTemp.getPrice().toString());
				if (AUTUNNO_INVERNO_17.equalsIgnoreCase(itemDO.getSeason().replaceAll("\\s*", ""))) {
					itemDO.setPriceDisplay(BigDecimalUtil
							.multiply(lenuxItemTemp.getPrice().toString(), AUTUNNO_INVERNO_17_DISCOUNT.toString())
							.toString());
				} else if (PRIMAVERA_ESTATE_17.equalsIgnoreCase(itemDO.getSeason().replaceAll("\\s*", ""))) {
					itemDO.setPriceDisplay(BigDecimalUtil
							.multiply(lenuxItemTemp.getPrice().toString(), PRIMAVERA_ESTATE_17_DISCOUNT.toString())
							.toString());
				} else if (AUTUNNO_INVERNO_16.equalsIgnoreCase(itemDO.getSeason().replaceAll("\\s*", ""))) {
					itemDO.setPriceDisplay(BigDecimalUtil
							.multiply(lenuxItemTemp.getPrice().toString(), AUTUNNO_INVERNO_16_DISCOUNT.toString())
							.toString());
				} else if (PRIMAVERA_ESTATE_16.equalsIgnoreCase(itemDO.getSeason().replaceAll("\\s*", ""))) {
					itemDO.setPriceDisplay(BigDecimalUtil
							.multiply(lenuxItemTemp.getPrice().toString(), PRIMAVERA_ESTATE_16_DISCOUNT.toString())
							.toString());
				} else {
					itemDO.setPriceDisplay("0");
				}
			}
		}
		itemDO.setFeatureValueDOList(propertyValueDOList);
		return itemDO;
	}

	public static void main(String[] args) {
		String url = "http://open.lenuxchina.com/api/item/page";// 应用地址
		String appid = "shxtest";// 账号
		String pageSize = "100";// 密码
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd%20HH:mm:ss");
		String timestamp = sdf.format(new Date());
		Map<String, String> nameValueMap = Maps.<String, String>newHashMap();
		nameValueMap.put("appid", appid);
		nameValueMap.put("pageSize", pageSize);
		nameValueMap.put("timestamp", timestamp);

		try {
			Set<String> brandSets = Sets.newHashSet();
			Set<String> catsSets = Sets.newHashSet();
			for (int page = 1; page < 200; page++) {
				nameValueMap.put("page", String.valueOf(page));
				String returnMessage = HttpContentGetter.getContentString(url, nameValueMap, null);
				System.out.println(returnMessage);
				// TODO 处理返回值,参见HTTP协议文档
				LenuxApiResult result = null;
				if (StringUtils.isNotEmpty(returnMessage)) {
					result = JSON.parseObject(returnMessage, LenuxApiResult.class);
					if (CollectionUtils.isEmpty(result.getData())) {
						System.out.println("End, page: " + page);
						break;
					} else {
						System.out.println("Page: " + page);
						for (LenuxProduct product : result.getData()) {
							brandSets.add(product.getBrand());
							catsSets.add(product.getCats());
							System.out.println("Product SPU: " + product.getSpu());
							// System.out.println("Product Brand: " +
							// product.getBrand());
							// System.out.println("Product Cats: " +
							// product.getCats());
							// System.out.println("Product Gender: " +
							// product.getGender());
							// System.out.println(
							// "Product Pic: " + product.getImgs().substring(0,
							// product.getImgs().indexOf(';')));
							if (null != product.getItems()) {
								for (LenuxItem lenuxItemTemp : product.getItems()) {
									String size = lenuxItemTemp.getSize();
									while (true) {
										if (null != size && size.startsWith("0")) {
											size = size.substring(1);
										} else {
											break;
										}
									}
									System.out.println("Item Size: " + size);
								}
							}
						}
					}
				}
			}
			for (String brand : brandSets) {
				System.out.println("brand: " + brand);
			}
			for (String cats : catsSets) {
				System.out.println("cats: " + cats);
			}
		} catch (Exception e) {
			// TODO 处理异常
			e.printStackTrace();
		}
	}

}
